package org.jeecg.modules.lab.cert.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.cronJob.MyEnum;
import org.jeecg.common.cronJob.entity.LabCronJob;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.lab.cert.client.UserClient;
import org.jeecg.modules.lab.cert.entity.LabCert;
import org.jeecg.modules.lab.cert.service.ILabCertService;
import org.jeecg.modules.lab.cert.vo.UserVo;
import org.jeecg.modules.lab.cronJob.service.ILabCronJobService;
import org.jeecg.modules.lab.exam.entity.LabExamPaper;
import org.jeecg.modules.lab.exam.paper.service.ILabExamPaperService;
import org.jeecg.modules.lab.flair.entity.LabFlair;
import org.jeecg.modules.lab.flair.service.ILabFlairService;
import org.jeecg.modules.lab.user.entity.SysUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 用户拥有的证书信息
 * @Author: jeecg-boot
 * @Date: 2023-09-04
 * @Version: V1.0
 */
@Api(tags = "用户拥有的证书信息")
@RestController
@RequestMapping("/cert/labCert")
@Slf4j
public class LabCertController extends JeecgController<LabCert, ILabCertService> {
    @Autowired
    private ILabCertService labCertService;
    @Autowired
    private UserClient userClient;
    @Autowired
    private ILabFlairService flairService;
    @Autowired
    private ILabExamPaperService examPaperService;
    @Autowired
    private ILabCronJobService labCronJobService;


    /**
     * 分页列表查询
     *
     * @param labCert
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "用户拥有的证书信息-分页列表查询")
    @ApiOperation(value = "用户拥有的证书信息-分页列表查询", notes = "用户拥有的证书信息-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<LabCert>> queryPageList(LabCert labCert,
                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                HttpServletRequest req) {
        QueryWrapper<LabCert> queryWrapper = QueryGenerator.initQueryWrapper(labCert, req.getParameterMap());
        Page<LabCert> page = new Page<LabCert>(pageNo, pageSize);
        IPage<LabCert> pageList = labCertService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @GetMapping(value = "/getCert")
    public Result<List<LabFlair>> getCert(){
        List<LabFlair> list = flairService.list();

//        List<String> strings = new ArrayList<>();
//        list.forEach(e->{
//            strings.add(e.getCertName());
//        });
        return Result.ok(list);
    }
    /**
     * 添加
     *
     * @param labCert
     * @return
     */
    @AutoLog(value = "用户拥有的证书信息-添加")
    @ApiOperation(value = "用户拥有的证书信息-添加", notes = "用户拥有的证书信息-添加")
//   @RequiresPermissions("cert:lab_cert:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody LabCert labCert) {
        labCertService.save(labCert);

        if (MyEnum.sync) {
            long time = new Date().getTime();
            LabCronJob job = new LabCronJob("lab_cert", "0", time, 1);
            labCronJobService.save(job);
        }
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param labCert
     * @return
     */
    @AutoLog(value = "用户拥有的证书信息-编辑")
    @ApiOperation(value = "用户拥有的证书信息-编辑", notes = "用户拥有的证书信息-编辑")
//   @RequiresPermissions("cert:lab_cert:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody LabCert labCert) {
        labCert.setSynFlag("1");
        labCertService.updateById(labCert);

        if (MyEnum.sync) {
            long time = new Date().getTime();
            LabCronJob job = new LabCronJob("lab_cert", "1", time, 1);
            labCronJobService.save(job);
        }
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "用户拥有的证书信息-通过id删除")
    @ApiOperation(value = "用户拥有的证书信息-通过id删除", notes = "用户拥有的证书信息-通过id删除")
//   @RequiresPermissions("cert:lab_cert:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        labCertService.removeById(id);

        if (MyEnum.sync) {
            long time = new Date().getTime();
            String condition="id='"+id+"'";
            LabCronJob job = new LabCronJob("lab_cert", "2", condition,time, 1);
            labCronJobService.save(job);
        }
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "用户拥有的证书信息-批量删除")
    @ApiOperation(value = "用户拥有的证书信息-批量删除", notes = "用户拥有的证书信息-批量删除")
//   @RequiresPermissions("cert:lab_cert:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.labCertService.removeByIds(Arrays.asList(ids.split(",")));

        if (MyEnum.sync) {
            long time = new Date().getTime();
            String[] idList = ids.split(",");
            labCronJobService.saveCronBatch("lab_cert","2",time,idList);
        }
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "用户拥有的证书信息-通过id查询")
    @ApiOperation(value = "用户拥有的证书信息-通过id查询", notes = "用户拥有的证书信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<LabCert> queryById(@RequestParam(name = "id", required = true) String id) {
        LabCert labCert = labCertService.getById(id);
        if (labCert == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(labCert);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param labCert
     */
//   @RequiresPermissions("cert:lab_cert:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, LabCert labCert) {
        return super.exportXls(request, labCert, LabCert.class, "用户拥有的证书信息");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
//   @RequiresPermissions("cert:lab_cert:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, LabCert.class);
    }

    //查询荣誉信息
    @GetMapping(value = "/listHonor")
    public Result<List<LabCert>> listHonor(@RequestParam(name = "id", defaultValue = "") String userId) {
        List<LabCert> list = labCertService.list(new LambdaQueryWrapper<LabCert>().eq(LabCert::getUserid, userId).eq(LabCert::getCertType, "荣誉"));
        return Result.ok(list);
    }

    @GetMapping(value = "/listFla")
    public Result<List<LabCert>> listFla(@RequestParam(name = "id", defaultValue = "") String userId) {
        List<LabCert> list = labCertService.list(new LambdaQueryWrapper<LabCert>().eq(LabCert::getUserid, userId).eq(LabCert::getCertType, "资质"));
        return Result.ok(list);
    }

    @GetMapping(value = "/listEdu")
    public Result<LabCert> listEdu(@RequestParam(name = "id", defaultValue = "") String userId) {
        LabCert cert = labCertService.getOne(new LambdaQueryWrapper<LabCert>().eq(LabCert::getUserid, userId).eq(LabCert::getCertType, "学历"));
        return Result.ok(cert);
    }

    @PostMapping(value = "/updateFair")
    public Result<String> updateFair(@RequestBody UserVo userVo) {
        String userId = userVo.getId();
        List<LabCert> honValue = userVo.getHonValue();
        List<LabCert> honList = labCertService.list(new LambdaQueryWrapper<LabCert>().eq(LabCert::getUserid, userId).eq(LabCert::getCertType, "荣誉"));
        List<String> honStr = new ArrayList<>();
        honList.forEach(e -> {
            honStr.add(e.getId());
        });

        List<String> listCondition = new ArrayList<>();//收集删除条件
        for (int i = 0; i < honValue.size(); i++) {
            honValue.get(i).setUserid(userId);
            if (honStr.contains(honValue.get(i).getId())) {
                honValue.get(i).setSynFlag("1");
                labCertService.updateById(honValue.get(i));
            } else {
                labCertService.save(honValue.get(i));
            }
        }
        for (String id : honStr) {
            boolean isDeleted = true;
            for (LabCert cert : honValue) {
                if (id.equals(cert.getId())) {
                    isDeleted = false; // 在honValue中找到对应的荣誉证书，不删除
                    break;
                }
            }
            // 如果在honValue中找不到对应的荣誉证书，则从数据库删除该证书
            if (isDeleted) {
                labCertService.remove(new LambdaQueryWrapper<LabCert>()
                        .eq(LabCert::getId, id)
                        .eq(LabCert::getCertType, "荣誉"));
                listCondition.add("id='"+id+"',"+"cert_type='"+"荣誉"+"'");
            }
        }
        List<LabCert> flaValue = userVo.getFlaValue();
        for (int i = 0; i < flaValue.size(); i++) {
            LabCert cert = flaValue.get(i);
            cert.setUserid(userId);
            LabFlair labFlair = flairService.getOne(new LambdaQueryWrapper<LabFlair>().eq(LabFlair::getFlaName, cert.getCertName()));
            if (labFlair==null){
                if(cert.getCertFile() != null && !"".equals(cert.getCertFile())){
                    cert.setResult("已通过");
                }else {
                    cert.setCertFile("无");
                    cert.setResult("未通过");
                }
            }else {
                cert.setCertFile("无");
                //判断资质考试是否通过
                //根据资质名称找到资质的考核内容
                cert.setCertId(labFlair.getId());
                    String[] split = labFlair.getExam().split(",");
                    for (int y = 0; y < split.length; y++) {
                        LabExamPaper paper = examPaperService.getOne(new LambdaQueryWrapper<LabExamPaper>().eq(LabExamPaper::getExamId, split[y]).eq(LabExamPaper::getUserId, userId));
                        if (paper == null || paper.getUserScore() < paper.getPassScore()) {
                            cert.setResult("待通过");
                            break;
                        } else {
                            cert.setResult("已通过");
                        }
                    }
            }
        }

        List<LabCert> flaList = labCertService.list(new LambdaQueryWrapper<LabCert>().eq(LabCert::getUserid, userId).eq(LabCert::getCertType, "资质"));
        List<String> flaStr = new ArrayList<>();
        flaList.forEach(e -> {
            flaStr.add(e.getId());
        });
        for (int i = 0; i < flaValue.size(); i++) {
            flaValue.get(i).setUserid(userId);
            if (flaStr.contains(flaValue.get(i).getId())) {
                flaValue.get(i).setSynFlag("1");
                labCertService.updateById(flaValue.get(i));
            } else {
                labCertService.save(flaValue.get(i));
            }
        }
        for (String id : flaStr) {
            boolean isDeleted = true;
            for (LabCert cert : flaValue) {
                if (id.equals(cert.getId())) {
                    isDeleted = false; // 在honValue中找到对应的荣誉证书，不删除
                    break;
                }
            }
            // 如果在flaValue中找不到对应的资质证书，则从数据库删除该证书
            if (isDeleted) {
                labCertService.remove(new LambdaQueryWrapper<LabCert>()
                        .eq(LabCert::getId, id)
                        .eq(LabCert::getCertType, "资质"));
                listCondition.add("id='"+id+"',"+"cert_type='"+"资质"+"'");
            }
        }
        if (userVo.getEducat() != null && StringUtils.isNotBlank(userVo.getEducat())) {
            LabCert labCert = new LabCert();
            labCert.setUserid(userVo.getId());
            labCert.setCertFile(userVo.getEducat());
            labCert.setCertType("学历");
            List<LabCert> eduList = labCertService.list(new LambdaQueryWrapper<LabCert>().eq(LabCert::getUserid, userId).eq(LabCert::getCertType, "学历"));
            if (eduList.size()==0){
                //第一次上传学历
                labCertService.save(labCert);
            }else {
                //第n次上传学历
                for (int i = 0; i < eduList.size(); i++) {
                    eduList.get(i);
                    listCondition.add("id='"+eduList.get(i).getId()+"'");
                }
                labCertService.removeBatchByIds(eduList);
                labCertService.save(labCert);
            }
        }else if ("".equals(userVo.getEducat())){
            listCondition.add("user_id='"+userVo.getId()+"',"+"cert_type='"+"学历"+"'");
            labCertService.remove(new LambdaQueryWrapper<LabCert>().eq(LabCert::getUserid, userVo.getId()).eq(LabCert::getCertType, "学历"));
        }


        if (MyEnum.sync) {
            long time = new Date().getTime();
            ArrayList<LabCronJob> jobs = new ArrayList<>();
           jobs.add(new LabCronJob("lab_cert", "0",time, 1));
           jobs.add(new LabCronJob("lab_cert", "1",time, 2));
            for (int i = 0; i < listCondition.size(); i++) {
                jobs.add(new LabCronJob("lab_cert", "2", listCondition.get(i),time, 3+i));
            }
            labCronJobService.saveBatch(jobs);
        }
        return Result.ok("修改成功");
    }

    @GetMapping(value = "/listFair")
    public Result<Page<UserVo>> listFair(SysUser user, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<SysUser> sysUserIPage = userClient.listUser(user, pageNo, pageSize);
        // 将实体类转化为DTO类
        List<UserVo> userVoList = sysUserIPage.getRecords().stream()
                .map(sysUser -> {
                    UserVo userVo = new UserVo();
                    BeanUtils.copyProperties(sysUser, userVo);
                    //根据员工id判断学历和荣誉证书的情况
                    String userId = sysUser.getId();
                    //判断学历
                    List<LabCert> eduList = labCertService.list(new LambdaQueryWrapper<LabCert>().eq(LabCert::getUserid, userId).eq(LabCert::getCertType, "学历"));
                    if (!eduList.isEmpty()) {
                        userVo.setEdu("已上传");
                    } else {
                        userVo.setEdu("未上传");
                    }
                    //判断荣誉
                    List<LabCert> honorList = labCertService.list(new LambdaQueryWrapper<LabCert>().eq(LabCert::getUserid, userId).eq(LabCert::getCertType, "荣誉"));
                    if (!honorList.isEmpty()) {
                        userVo.setHonor("已上传");
                    } else {
                        userVo.setHonor("未上传");
                    }
                    return userVo;
                }).collect(Collectors.toList());

        // 返回DTO分页数据
        Page<UserVo> page = new Page<>(sysUserIPage.getCurrent(), sysUserIPage.getSize(), sysUserIPage.getTotal());
        page.setRecords(userVoList);
        return Result.ok(page);
    }
}
